﻿using System.Numerics;
using TouchTable;
using TouchTable.Input;
using PointerType = TouchTable.Point.PointerType;

namespace UnityTouchTable.Runtime
{
    /// <summary>
    /// 鼠标输入源
    /// </summary>
    internal class MouseInput : BaseInputSource
    {
        #region 字段
        /// <summary>
        /// 鼠标ID
        /// </summary>
        private int m_MouseID;

        /// <summary>
        /// 上一帧的位置
        /// </summary>
        private Vector2 m_LastMousePostion;
        #endregion

        /// <summary>
        /// 构造函数
        /// </summary>
        public MouseInput()
        {

        }

        #region BaseFunction
        /// <summary>
        /// 初始化
        /// </summary>
        public override void OnInit()
        {
            base.OnInit();

            this.m_LastMousePostion = this.Remap(new Vector2(UnityEngine.Input.mousePosition.x, UnityEngine.Input.mousePosition.y));
            this.m_MouseID = this.AddPointer(this.m_LastMousePostion, PointerType.MOUSE);
        }

        /// <summary>
        /// 当轮训时
        /// </summary>
        public override void OnUpdate()
        {
            base.OnUpdate();

            Vector2 currentMousePostion = this.Remap(new Vector2(UnityEngine.Input.mousePosition.x, UnityEngine.Input.mousePosition.y));
            if (this.m_LastMousePostion != currentMousePostion)
            {
                this.UpdatePointer(this.m_MouseID, currentMousePostion);
                this.m_LastMousePostion = currentMousePostion;
            }
        }

        /// <summary>
        /// 当销毁时
        /// </summary>
        public override void OnBreak()
        {
            base.OnBreak();

            this.RemovePointer(this.m_MouseID);
            this.m_LastMousePostion = Vector2.Zero;
        }
        #endregion

        #region Function
        /// <summary>
        /// 重映射
        /// </summary>
        /// <param name="currentMousePostion">待映射的鼠标位置</param>
        /// <returns>映射后的鼠标位置</returns>
        private Vector2 Remap(Vector2 currentMousePostion)
        {
            currentMousePostion.X = Mathf.Clamp(currentMousePostion.X, 0.0f, Parameter.Screen.X);
            currentMousePostion.Y = Mathf.Clamp(currentMousePostion.Y, 0.0f, Parameter.Screen.Y);
            return currentMousePostion;
        }
        #endregion
    }
}